package com.estar.assistsurvy.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import com.estar.app.appsrvyspds.domain.ReturnSubVideoSrvyVO;
import com.estar.assistsurvey.entity.ImageVO;
import com.estar.assistsurvy.R;
import com.estar.assistsurvy.adapter.PicturePagerAdapter;
import com.estar.assistsurvy.database.PhotoService;
import com.estar.assistsurvy.entity.ScalePagerItem;
import com.estar.assistsurvy.service.ImageService;
import com.estar.assistsurvy.utils.FileUtil;
import com.estar.assistsurvy.utils.TimeUtils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class TakePictureActivity extends BaseActivity implements OnClickListener,OnPageChangeListener{

	private Button topButton;
	private ImageView bottomButton,takePhoto,photoPreview;
	private LinearLayout container;
	private SurfaceView surfaceView;
	private Camera camera;
	private Camera.Parameters parameters=null;
//	private static final String PIC_HOME=Environment.getExternalStorageDirectory()+File.separator+"Pictures/";
//	private String filename;
	private Bundle bundle = null; // 声明一个Bundle对象，用来存储数据  
//	private 
	private ViewPager picturePager;
	private PicturePagerAdapter adapter;
	private Intent intent;
	private ArrayList<ScalePagerItem> list;
	private ReturnSubVideoSrvyVO returnSubVideoSrvyVo;
	private ArrayList<ImageView> views;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_takepicture);
		initView();
	}

	@SuppressWarnings({ "deprecation", "unchecked" })
	private void initView(){
		topButton=find(R.id.topButton);
		topButton.setOnClickListener(this);
		bottomButton=find(R.id.bottomButton);
		bottomButton.setOnClickListener(this);
		takePhoto=find(R.id.takePhoto);
		takePhoto.setOnClickListener(this);
		photoPreview=find(R.id.photoPreview);
		photoPreview.setOnClickListener(this);
		
		intent=getIntent();
		returnSubVideoSrvyVo = (ReturnSubVideoSrvyVO) intent.getSerializableExtra("returnSubVideoSrvyVO");

		list=(ArrayList<ScalePagerItem>) intent.getExtras().get("list");
		picturePager=find(R.id.picturePager);
		adapter=new PicturePagerAdapter(list, TakePictureActivity.this);
//		adapter.setViews(list, TakePictureActivity.this);
		picturePager.setAdapter(adapter);
		picturePager.addOnPageChangeListener(this);
		
		new PhotoService(TakePictureActivity.this);
		
		container=find(R.id.container);
		views=new ArrayList<>();
		for(int i=0;i<list.size();i++){
			ImageView imageview=new ImageView(TakePictureActivity.this);
			container.addView(imageview);
			views.add(imageview);
		}
		clearState();
		views.get(0).setImageResource(R.drawable.image_indicator_focus);
		surfaceView=find(R.id.surfaceView);
		surfaceView.getHolder()  
		.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
		surfaceView.getHolder().setFixedSize(176, 144); //设置Surface分辨率  
		surfaceView.getHolder().setKeepScreenOn(true);// 屏幕常亮  
		surfaceView.getHolder().addCallback(new SurfaceCallback());//为SurfaceView的句柄添加一个回调函数  
	}

	private final class SurfaceCallback implements Callback{

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			try {
				camera = Camera.open(); // 打开摄像头  
				camera.setPreviewDisplay(holder); // 设置用于显示拍照影像的SurfaceHolder对象  
				camera.setDisplayOrientation(0); // 设置拍照角度
				camera.startPreview(); // 开始预览  
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@SuppressWarnings("deprecation")
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
			// TODO Auto-generated method stub
			parameters = camera.getParameters(); // 获取各项参数  
			parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式  
			parameters.setPreviewSize(width, height); // 设置预览大小  
			parameters.setPreviewFrameRate(5);  //设置每秒显示4帧  
			parameters.setPictureSize(width, height); // 设置保存的图片尺寸  
			parameters.setJpegQuality(80); // 设置照片质量  
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			if (camera != null) {  
				camera.release(); // 释放照相机  
				camera = null;  
			} 
		}

	}
	
	/**
	 * 闪光灯
	 *
	 * @param value
	 */
	private boolean isOpenLamp=true;
	public void openLamp() {

		Parameters parameter = camera.getParameters();  
		
		if(isOpenLamp){
			camera.startPreview();
			
			parameter.setFlashMode(Parameters.FLASH_MODE_TORCH);

			camera.setParameters(parameter);
			
			isOpenLamp=false;
		}else{
			parameter.setFlashMode(Parameters.FLASH_MODE_OFF);

			camera.setParameters(parameter);
			
			isOpenLamp=true;
		}

	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.topButton:
			intent=new Intent(TakePictureActivity.this, DemagedPositionActivity.class);
			startActivity(intent);
			finish();
			break;

		case R.id.bottomButton:
			openLamp();
			break;

		case R.id.takePhoto:
			if (camera != null) {  
				// 拍照  
				camera.takePicture(null, null, new MyPictureCallback());  
			}else{
				showShortToast("摄像头未打开!");
			}
			break;
			
		case R.id.photoPreview:
			intent=new Intent(TakePictureActivity.this, PhotoPreviewActivity.class);
			intent.putExtra("rptNo", returnSubVideoSrvyVo.getTaskNo());
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	private final class MyPictureCallback implements PictureCallback {  

		@Override  
		public void onPictureTaken(byte[] data, Camera camera) {  
			try {  
				bundle = new Bundle();  
				bundle.putByteArray("bytes", data); //将图片字节数据保存在bundle当中，实现数据交换  
//				saveToSDCard(data); // 保存图片到sd卡中  
//				new SavePicture().execute(data);// 保存图片到sd卡中  
				//showShortToast("拍摄成功!"); 
				camera.startPreview(); // 拍完照后，重新开始预览  
				new SavePicTask(data).execute();
			} catch (Exception e) {  
				e.printStackTrace();  
			}  
		}  
	} 
	
	private class SavePicTask extends AsyncTask<Void,Void,String>{
		private byte[] picData;
		private String imagePath;
		public SavePicTask(byte[] picData){
			this.picData = picData;
		}
		@Override
		protected String doInBackground(Void... params) {
			imagePath = FileUtil.getImageDirectory("IMG"+TimeUtils.getDetailDate()+".jpg");
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(imagePath);
				fos.write(picData,0,picData.length);
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				if(fos!=null){
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			File file = null;
			if((file = new File(imagePath)).exists()){
				
				ImageVO imageVO = new ImageVO();
				imageVO.setPicPath(imagePath);
				imageVO.setRptNo(returnSubVideoSrvyVo.getTaskNo());
				imageVO.setCarNo(returnSubVideoSrvyVo.getCarNo());
				imageVO.setCompCde("");
				imageVO.setDptCde("32000002");
				imageVO.setPicName(file.getName());
				imageVO.setPicPath(imagePath);
				imageVO.setPicDescription("");
				imageVO.setLongitude("");
				imageVO.setLatitude("");
				imageVO.setCreateTm(TimeUtils.getDate());
				imageVO.setClaimTaskId(returnSubVideoSrvyVo.getClaimTaskId());
				imageVO.setClaimTaskType(returnSubVideoSrvyVo.getClaimTaskType());
				imageVO.setLossEmpCde(returnSubVideoSrvyVo.getSetLossCde());
				imageVO.setLossEmpNme(returnSubVideoSrvyVo.getSetLossNme());
				imageVO.save();
				startService(new Intent(TakePictureActivity.this, ImageService.class));
			}
			
			return "ok";
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if(result.equals("ok")){
//				Drawable drawable=Drawable.createFromPath(imagePath);
//				showShortToast("图片上传成功!"); 
//				if(currentItem==-1){
//					list.get(0).setPicPath(imagePath);
//					setCommitDialog();
//				}else{
					list.get(currentItem).setPicPath(imagePath);
					if(currentItem<list.size()-1){
						setDialog();
					}else{
						setCommitDialog();
					}
//				}
				
				adapter.notifyDataSetChanged();
				
//				adapter=new PicturePagerAdapter(list, TakePictureActivity.this);
//				picturePager.setAdapter(adapter);
//				picturePager.setCurrentItem(currentItem+1);
			}
		}
	}
	
	private void setDialog(){
		new AlertDialog.Builder(TakePictureActivity.this, AlertDialog.THEME_HOLO_LIGHT)
		.setMessage("图片上传成功!")
		.setPositiveButton("下一张", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				picturePager.setCurrentItem(currentItem+1);
			}
		})
		.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		})
		.create().show();
	}
	
	private void setCommitDialog(){
		new AlertDialog.Builder(TakePictureActivity.this, AlertDialog.THEME_HOLO_LIGHT)
		.setMessage("图片上传成功!")
		.setNegativeButton("完成", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				intent=new Intent(TakePictureActivity.this, DemagedPositionActivity.class);
				startActivity(intent);
				finish();
			}
		})
		.create().show();
	}

//	private class SavePicture extends AsyncTask<byte[], String, String>
//	{
//		File file;
//		@Override
//		protected String doInBackground(byte[]... params) {
//			byte[] param=params[0];
//			File fileFolder = new File(PIC_HOME); 
//			if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录  
//				fileFolder.mkdir();  
//			}
//			filename="照片_"+System.currentTimeMillis()+".jpeg";
//			file=new File(fileFolder,filename);
//			try {
//				FileOutputStream out=new FileOutputStream(file);
//				out.write(param);
//				out.flush();
//				out.close();
//			} catch (FileNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			if(file .exists()){
//				ImageVO imageVO = new ImageVO();
//				imageVO.setPicPath(file.getAbsolutePath());
//				imageVO.setRptNo(returnSubVideoSrvyVo.getTaskNo());
//				imageVO.setCarNo(returnSubVideoSrvyVo.getCarNo());
//				imageVO.setCompCde("");
//				imageVO.setDptCde("32000002");
//				imageVO.setPicName(file.getName());
//				imageVO.setPicPath(file.getAbsolutePath());
//				imageVO.setPicDescription("");
//				imageVO.setLongitude("");
//				imageVO.setLatitude("");
//				imageVO.setCreateTm(TimeUtils.getDate());
//				imageVO.setClaimTaskId(returnSubVideoSrvyVo.getClaimTaskId());
//				imageVO.setClaimTaskType(returnSubVideoSrvyVo.getClaimTaskType());
//				imageVO.setLossEmpCde(returnSubVideoSrvyVo.getSetLossCde());
//				imageVO.setLossEmpNme(returnSubVideoSrvyVo.getSetLossNme());
//				imageVO.save();
//				startService(new Intent(TakePictureActivity.this, ImageService.class));
//			}
//			return "ok";
//
//		}
//
//		@Override
//		protected void onPostExecute(String result) {
//			if(result.equals("ok")){
//				Drawable drawable=Drawable.createFromPath(file.getAbsolutePath());
////				scalePic.setImageDrawable(drawable);
//				showShortToast("拍摄成功!"); 
//				list.get(picturePager.getCurrentItem()).setDrawables(drawable);
//				adapter.setViews(list, TakePictureActivity.this);
////				adapter.notifyDataSetChanged();
//				picturePager.setAdapter(adapter);
//				picturePager.setCurrentItem(currentItem);
//			}
//		}
//
//	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		currentItem=position;
		clearState();
		views.get(position).setImageResource(R.drawable.image_indicator_focus);
		
	}
	private int currentItem=0;
	
	private void clearState(){
		for(int i=0;i<list.size();i++){
			views.get(i).setImageResource(R.drawable.image_indicator);
		}
	}

	//	public static void saveToSDCard(byte[] data) throws IOException {  
	//        Date date = new Date();  
	//        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间  
	//        String filename = format.format(date) + ".jpg";  
	//        File fileFolder = new File(Environment.getExternalStorageDirectory()  
	//                + "/finger/");  
	//        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录  
	//            fileFolder.mkdir();  
	//        }  
	//        File jpgFile = new File(fileFolder, filename);  
	//        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流  
	//        outputStream.write(data); // 写入sd卡中  
	//        outputStream.close(); // 关闭输出流  
	//    } 
}
